<?php
/**
 * Classe para gerenciamento de conteúdos
 * Author: Bruno Ramos <contato [AT] brunoramos [DOT] eti [DOT] br>
 * File: conteudo.class.php
 * Version: 1.0
 */
 
 
/************************* Consult pg *************************/
function smarty_function_consultas($params, Smarty_Internal_Template $template) {
	$config = $template->getconfigVars();
	extract($params);
        $assign = $params["assign"];
	PDO4You::getInstance();
		
	if ($params["tipo"] == "conteudo") {
            $cont = $cat = null;
            if(!empty($params["cont"]) && $params["cont"] != "*") {
                $aux = explode(",", $params["cont"]);
                $r = "(";
                for($i=0;$i<sizeof($aux);$i++) {
                    $r .= "conteudos.url='".$aux[$i]."'";
                    if($i+1 != sizeof($aux))
                        $r.= " OR ";
                }
                $cont = $r.") AND";
            }
            if(!empty($params["cat"])) {
                $aux = explode(",", $params["cat"]);
                $r = "(";
                for($i=0;$i<sizeof($aux);$i++) {
                    $r .= "categorias.url='".$aux[$i]."'";
                    if($i+1 != sizeof($aux))
                        $r.= " OR ";
                }
                $cat = $r.") AND";
            }
	    
            if (!empty($params["cont"]) || $params["cont"] == "*") {
                $order = (isset($params["order"]))? $params["order"] : "conteudos.titulo ASC";
                $query = "
                    SELECT 
                            categorias.titulo AS tituloCat, 
                            conteudos.titulo AS tituloCont, 
                            descricao, 
                            conteudos.resumo AS resumoCont,
                            categorias.resumo AS resumoCat, 
                            conteudos.id AS idCont, 
                            categorias.id AS idCat,
                            conteudos.url AS urlCont,
                            categorias.url AS urlCat,
                            conteudos.img AS imgCont
                        FROM 
                            conteudos INNER JOIN categorias ON 
                                    (conteudos.id_pai=categorias.id_link)
                    WHERE 
                            ($cat $cont categorias.id_idioma=conteudos.id_idioma AND conteudos.id_idioma=".$_SESSION["langId"].")
                    ORDER BY
                            $order
                ";
            }
            else {
                $order = (isset($params["order"]))? $params["order"] : "categorias.titulo ASC";
                
                    $query = "
                    SELECT 
                            categorias.titulo AS tituloCat, 
                            categorias.resumo AS resumoCat, 
                            categorias.id AS idCat,
                            categorias.url AS urlCat
                        FROM 
                            categorias
                    WHERE 
                            ($cat categorias.id_idioma=".$_SESSION["langId"].")
                    ORDER BY
                            $order;
                ";
            }
            if ($params['debug'] > 0) {
                    echo "<pre>".$query."</pre>";
                    if($params['debug'] == 2) $template->debugging = TRUE;
            }
            $consulta = PDO4You::select($query);
            $template->assign($assign, $consulta);
            if($params["menu"]) {
                    $query = "
                            SELECT 
                                    conteudos.titulo AS tituloCont, 
                                    conteudos.url AS urlCont
                            FROM 
                                    categorias INNER JOIN conteudos ON 
                                    ($cat AND conteudos.id_pai=categorias.id_link AND categorias.id_idioma=conteudos.id_idioma AND conteudos.id_idioma=".$_SESSION["langId"].")
                            ORDER BY
                                    conteudos.id
                        ";
                        $consulta = PDO4You::select($query);
                        $template->assign("menu", $consulta);
            }
	} else if ($params["tipo"] == "categoria") {
            if (!empty($params["parent"]))
                $query = "
                    SELECT 
                        titulo, url, resumo
                    FROM 
                        categorias
                    WHERE 
                        id_idioma=".$_SESSION["langId"]." AND 
                        id_pai=(
                            SELECT 
                                id_link
                            FROM 
                                categorias 
                            WHERE 
                                url='".$params["parent"]."' AND 
                                id_idioma=".$_SESSION["langId"]." 
                            LIMIT 1
                        )
                    ORDER BY
                        ".$params["order"]." ASC
                ";
                if ($params['debug'] > 0) {
                    echo "<pre>".$query."</pre>";
                    if($params['debug'] == 2) $template->debugging = TRUE;
                }
                $consulta = PDO4You::select($query);
                $template->assign($assign, $consulta);
        } else {
		//Pagination
		$pagina = (!isset($params['pg_atual']) || $params['pg_atual'] == 0)? 0 : $params['pg_atual']-1;
		
		$link = $params['link'];
		$num_por_pagina = $limit_value = (isset($params['limit']))? $params["limit"] : 0;
		$primeiro_registro = ($pagina*$num_por_pagina) - $num_por_pagina;
		//End Pagination
	
		$select = $params['select']; if ($select==NULL) $select = "*";
		$tabela = $params['tabela'];
		if ($limit_value != 0)
			$limit = " LIMIT ".$limit_value." OFFSET ".($pagina*$limit_value);
			
		$order = $params['order']; if ($order=="0" or empty($order)) $order = ""; else $order = " ORDER BY ".$order;
		$ativo = $params['ativo']; if (empty($ativo)|| $ativo=="0") $ativo = ""; else $ativo = " AND ativo= ".$ativo;
		$where = $params['where']; if (empty($where)) $where = ""; else $where = " WHERE ".$where;
		$assign = $params['assign'];
		
		//Connection
		$query = "SELECT ".$select." FROM ".$tabela.$where.$ativo.$order.$limit;
		
		//Debug
		if ($params['debug'] > 0) {
			echo "<pre>".$query."</pre>";
			if($params['debug'] == 2) $template->debugging = TRUE;
		}
		$consulta = PDO4You::select($query);
		$template->assign($assign, $consulta);
	
		
		/* Paginacao */
		if (!empty($link)) {
			
			$result = PDO4You::select("SELECT ".$select." FROM ".$tabela.$where.$order);
			$total_usuarios = PDO4You::rowCount();
			$pagina++;
			if($total_usuarios > $qtd) {
				$total_paginas = ceil($total_usuarios/$num_por_pagina);
				$prev = $pagina+ - 1;
				$next = $pagina + 1;
				if ($pagina > 1)
					$prev_link = "<a href=\"".$link."/$prev\">".$config['pg_prev']."</a>";
				else
					$prev_link = "<span class='nolink_ant'>".$config['pg_prev']."</span>";
				
				
				if ($total_paginas > $pagina)
					$next_link = "<a href=\"".$link."/$next\">".$config['pg_next']."</a>";
				else
					$next_link = "<span class='nolink_p'>".$config['pg_next']."</span>";
					
				$x = $pagina - 3; if($x <= 1) $x = 1;
				$total = $pagina + 3; if($total >$total_paginas) $total = $total_paginas;
				for (; $x<=$total; $x++) {
					if ($x == $pagina)
						if($total_paginas == 1)
							$painel .= "&nbsp;<span class='nolink'>$x</span>&nbsp;";
						else
							$painel .= "&nbsp;<span class='nolink'>$x</span>&nbsp;";
					else 
						$painel .= "&nbsp<a href=\"".$link."/$x\">$x</a>&nbsp;";	
					
				}
				$retc = $total_paginas - $total;
				if($retc < 1 ) $more = "";
				elseif ($retc == 1) $more = "<a href=".$link."/".$total_paginas.">".$total_paginas."</a>&nbsp;";
				else {
					$more = "<a href=".$link."/".++$total.">...</a>&nbsp;";
					$more .= "<a href=".$link."/".$total_paginas.">".$total_paginas."</a>&nbsp;";
				}
				
				if($pagina >= 5) {
					$voltar = "<a href=".$link."/1>1</a>"; 
					$back = $pagina - 4; 
					if($pagina != 5) $voltar .= " <a href=".$link."/".$back.">...</a>";
				}
	
				$painel = "$prev_link $voltar $painel $more $next_link";
				$template->assign('painel', $painel);
			}
			if($total_usuarios==0)
				$template->assign('painel',  "");
		}
	}
}
/************************* END Consult pg *************************/

/************************* Album *************************/
function smarty_function_album($params, Smarty_Internal_Template $template) {
	$config = $template->getconfigVars();
	extract($params);
	PDO4You::getInstance();
	$limite = (empty($params["limite"]))? 0 : $params["limite"];
	$col = (empty($params["colunas"]))? 1 : $params["colunas"];
	$url = $params["url"];
	$pag = (empty($params["pag"]))? 1 : $params["pag"];
	
	//Pagination
	$pagina = (!isset($params['pg_atual']) || $params['pg_atual'] == 0)? 0 : $params['pg_atual']-1;
	$link = $params['link'];
	$num_por_pagina = $limit_value = $limite;
	$primeiro_registro = ($pagina*$num_por_pagina) - $num_por_pagina;
	//End Pagination
	if ($limit_value != 0)
		$limit = " LIMIT ".$limit_value." OFFSET ".($pagina*$limit_value);
	
	
	if(!empty($url)) {			
		$query = "
			SELECT 
				images.arquivo AS img,
				conteudos.titulo AS titulo
			FROM 
				images INNER JOIN conteudos ON 
				(conteudos.url='".$url."' AND images.id_pai=conteudos.id)
		 	ORDER BY
				images.id
		 ";
		$consulta = PDO4You::select($query.$limit);
		$baseUrl = 'http://'.$_SERVER['HTTP_HOST'];
		$total = PDO4You::rowCount();
		if ($total > 0) {
			/* Paginacao */	
			$result = PDO4You::select($query);
			$total_usuarios = PDO4You::rowCount();
			$pagina++;
			if($total_usuarios > $qtd) {
				$total_paginas = ceil($total_usuarios/$num_por_pagina);
				$prev = $pagina+ - 1;
				$next = $pagina + 1;
				if ($pagina > 1)
					$prev_link = '<a href="'.$link.'/'.$prev.'" class="album_left" title="Anterior"><span>Anterior</span></a>';
				else
					$prev_link = '<a href="javascript:preventDefault();" class="album_left" title="Anterior"><span>Anterior</span></a>';
				
				
				if ($total_paginas > $pagina)
					$next_link = '<a href="'.$link.'/'.$next.'" class="album_right" title="Pr&oacute;ximo"><span>Pr&oacute;ximo</span></a>';
				else
					$next_link = '<a href="javascript:preventDefault()" class="album_right" title="Pr&oacute;ximo"><span>Pr&oacute;ximo</span></a>';
					
				for ($x=1; $x <= $total_paginas; $x++) {
					$linkClass = ($x == $pagina)? 'class="albumActive" ' : null;
					
					$output.='<li><a '.$linkClass.'href="'.$link.'/'.$x.'" title="'.$x.'">'.$x.'</a></li>';			
				}
			}
					 
			 //visualizacao
			 echo '
				<div id="album">
						<div id="album_wrap" class="corner">
							<div id="album_content">
								'.$prev_link.$next_link.'
								<ul>';
								
								for($i=0;$i<$total;$i++) {
									if($i != 0 && $i % $colunas == 0)
										echo '
											<li class="clear">
										';								
									else
										echo '
											<li>
										';
									
									echo '<a href="'.$baseUrl.'/img/cont/'.$consulta[$i]["img"].'" title="'.$consulta[$i]["titulo"].'" rel="galeria"><img src="'.$baseUrl.'/img/cont/thumb_'.$consulta[$i]["img"].'" /></a></li>';
								}
			 
			  echo '
								 </ul>
								<br class="clear" />
								<div id="album_nav">
									<ul>
										'.$output.'
									</ul>
								</div>
							</div>
						</div>
					</div>
			 ';
		}
	}
}
?>